package com.zyw.security.shiro.stateless.filter;

import com.zyw.security.shiro.stateless.realm.StatelessToken;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authz.AuthorizationFilter;
import org.apache.shiro.web.util.WebUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录认证filter
 *
 * @author zhangyw
 * @date 2017/12/6 14:46
 */
public class StatelessAuthcFilter extends AuthorizationFilter {

    /**
     * 控制台路径
     */
    private String pathConsolePattern;
    /**
     * 接口服务路径
     */
    private String pathRestPattern;

    public void setPathConsolePattern(String pathConsolePattern) {
        this.pathConsolePattern = pathConsolePattern;
    }

    public String getPathConsolePattern() {
        return pathConsolePattern;
    }

    public void setPathRestPattern(String pathRestPattern) {
        this.pathRestPattern = pathRestPattern;
    }

    public String getPathRestPattern() {
        return pathRestPattern;
    }

    private boolean isConsoleRequest(ServletRequest request, ServletResponse response) {
        return pathMatcher.matches(getPathConsolePattern(), getPathWithinApplication(request));
    }

    private boolean isRestRequest(ServletRequest request) {
        return pathMatcher.matches(getPathRestPattern(), getPathWithinApplication(request));
    }

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        return isLoginRequest(request, response);
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {

        HttpServletRequest httpServletRequest = WebUtils.toHttp(request);

        StatelessToken statelessToken = new StatelessToken();
        statelessToken.setToken(httpServletRequest.getHeader("token"));
        statelessToken.setAgent(httpServletRequest.getHeader("agent"));

        Subject subject;
        try {
            subject = getSubject(request, response);
            subject.login(statelessToken);
        } catch (AuthenticationException e) {
            WebUtils.toHttp(response).sendError(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }

        return true;
    }

}
